package com.uduemc.biso.node.web.api.validator.currentsite.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.dto.download.DownloadBaseAttr;
import com.uduemc.biso.node.web.api.service.DownloadService;
import com.uduemc.biso.node.web.api.validator.currentsite.CurrentSiteListSDownloadAttrContentIdExist;

public class CurrentSiteListSDownloadAttrContentIdExistValid
		implements ConstraintValidator<CurrentSiteListSDownloadAttrContentIdExist, List<DownloadBaseAttr>> {

	private static final Logger logger = LoggerFactory.getLogger(CurrentSiteListSDownloadAttrContentIdExistValid.class);

	@Override
	public void initialize(CurrentSiteListSDownloadAttrContentIdExist constraintAnnotation) {

	}

	@Override
	public boolean isValid(List<DownloadBaseAttr> value, ConstraintValidatorContext context) {
		if (CollectionUtils.isEmpty(value)) {
			return true;
		}
		List<Long> contentIds = new ArrayList<>();
		for (DownloadBaseAttr attr : value) {
			if (attr.getContenId() > 0) {
				contentIds.add(attr.getContenId());
			}
		}
		if (CollectionUtils.isEmpty(contentIds)) {
			return true;
		}

		// 验证 ids 是否均是当前站点的数据
		DownloadService downloadServiceImpl = SpringContextUtils.getBean("downloadServiceImpl", DownloadService.class);
		boolean bool = false;
		try {
			bool = downloadServiceImpl.existCurrentAttrContentInfosByIds(contentIds);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!bool) {
			logger.error(
					"通过 downloadServiceImpl.existCurrentAttrContentInfosByIds(ids) 验证，无法断定数据正确。 ids: " + contentIds);
			return false;
		}

		return true;
	}

}
